package com.softcits.email.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

import org.apache.commons.io.IOUtils;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.softcits.email.model.MailInfo;
import com.softcits.email.quartz.SoftCitsConnectionProvider;

@Service
public class EmailService {
    
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Value("${mail.ServerHost}")
    private String serverHost;

    @Value("${mail.SenderAddress}")
    private String senderAddress;

    @Value("${mail.SenderNick}")
    private String senderNick;

    @Value("${mail.SenderUsername}")
    private String senderUsername;

    @Value("${mail.SenderPassword}")
    private String senderPassword;

    public boolean sendEmail(MailInfo info) throws EmailException {
        HtmlEmail email = new HtmlEmail();
        email.setHostName(this.serverHost);
        email.setFrom(senderAddress, senderNick);
        email.setAuthentication(senderUsername, senderPassword);
        email.setCharset("UTF-8");
        
        
        email.setSubject(info.getSubject());
        email.setTextMsg(info.getContent());
        
        List<String> toList = info.getToAddress();
        if(toList == null || toList.isEmpty()) {
            throw new EmailException("Please specify Target Email Addresses ");
        }
        
        for(String add : toList) {
            email.addTo(add);
        }
        
        List<String> ccList = info.getCcAddress();
        if(ccList != null) {
            for(String cc: ccList) {
                email.addCc(cc);
            }
        }
        
        List<String> bccList = info.getBccAddress();
        if(ccList != null) {
            for(String bcc: bccList) {
                email.addBcc(bcc);
            }
        }
       
        if(info.getFiles() != null) {
            try {
                File root = new File("./files");
                if(!root.exists()) {
                    root.mkdirs();
                }
                for(MultipartFile file : info.getFiles()) {
                    InputStream is = file.getInputStream();
                    File destFile = new File(root, file.getOriginalFilename());
                    if(!destFile.exists()) {
                        FileOutputStream fos = new FileOutputStream(destFile);
                        IOUtils.copy(is, fos);
                        IOUtils.closeQuietly(fos);
                    }
                    
                    EmailAttachment attachement = new EmailAttachment();
                    attachement.setPath(destFile.getPath());
                    info.getAttachments().add(attachement);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            
        }
        
        for(EmailAttachment att: info.getAttachments()) {
            // when add email attachment, it is required to call [attach],
            email.attach(att);
        }
        
        email.send();
        
        return true;
    }
    
    public void sendEmailByJob(MailInfo info) {
        
    }
    
    public List<String> getAllEmailAddresses() {
        
        String sql = "select distinct email from e_user where status = '1'";
        List<String> toAdds = this.jdbcTemplate.query(sql, new ResultSetExtractor<List<String>>() {
            List<String> mList = new ArrayList<>();
            @Override
            public List<String> extractData(ResultSet rs) throws SQLException, DataAccessException {
                while(rs.next()) {
                    mList.add(rs.getString("email"));
                }
                return mList;
            }
            
        });

        return toAdds;
    }
}
